package com.impc.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest request, Exception e) {
        logger.error("【系统异常】{}", e);
        if(isAjax(request)){
            if (e instanceof MyException) {
                MyException myException = (MyException) e;
                return Result.error(myException.getCode(), myException.getMessage());
            }else {
                return Result.error(e);
            }
        }else{

            ModelAndView mav =new ModelAndView();
            mav.addObject("exception",e);
            mav.addObject("url",request.getRequestURL());
            mav.setViewName("/error");
            if (e instanceof MyException) {
                MyException myException = (MyException) e;
                mav.addObject("code",myException.getCode());
                mav.addObject("msg",myException.getMessage());
            }
            return mav;
        }

    }

    /**
     * 判断是否是ajax请求
     * @param httpRequest
     * @return
     */
    public static boolean isAjax(HttpServletRequest httpRequest){
        return (httpRequest.getHeader("X-Requested-With") != null && "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With")));
    }
}
